#!/bin/bash

# no set -euo pipefail as a lot of the greps below are expected to fail
# no cki_utils.sh use so this script can be curled and executed on its own

# shellcheck disable=SC2312

MR_IMAGE_TAG_COUNT=1
PIPELINE_IMAGE_TAG_COUNT=1

raw_images=$(docker image ls --format '{{.Repository}}:{{.Tag}}')

# keep all latest images
keep_latest_images=$(echo "${raw_images}" | grep ":latest$")
if (( "$(echo "${keep_latest_images}" | wc -w)" > 0 )); then
  echo "Keeping latest images:"
  echo "${keep_latest_images}" | sed 's/^/  /' | sort
  raw_images=$(echo "${raw_images}" | grep -vF "${keep_latest_images}")
fi

# keep all production images
keep_production_images=$(echo "${raw_images}" | grep ":production$")
if (( "$(echo "${keep_production_images}" | wc -w)" > 0 )); then
  echo "Keeping production images:"
  echo "${keep_production_images}" | sed 's/^/  /' | sort
  raw_images=$(echo "${raw_images}" | grep -vF "${keep_production_images}")
fi

# keep latest mr-123 images
keep_mr_tags=$(echo "${raw_images}" | sed 's/.*://' | grep '^mr-' | sort -unrk 1.4 | head -n "${MR_IMAGE_TAG_COUNT}")
if (( "$(echo "${keep_mr_tags}" | wc -w)" > 0 )); then
  echo "Keeping latest MR tags:"
  echo "${keep_mr_tags}" | sed 's/^/  /' | sort
  # shellcheck disable=SC2001
  keep_mr_images=$(echo "${raw_images}" | grep "$(echo "${keep_mr_tags}" | sed 's/.*/:&$/')")
  echo "Keeping latest MR images:"
  echo "${keep_mr_images}" | sed 's/^/  /' | sort
  raw_images=$(echo "${raw_images}" | grep -vF "${keep_mr_images}")
fi

# keep latest p-123 images
keep_pipeline_tags=$(echo "${raw_images}" | sed 's/.*://' | grep '^p-' | sort -unrk 1.3 | head -n "${PIPELINE_IMAGE_TAG_COUNT}")
if (( "$(echo "${keep_pipeline_tags}" | wc -w)" > 0 )); then
  echo "Keeping latest pipeline tags:"
  echo "${keep_pipeline_tags}" | sed 's/^/  /' | sort
  # shellcheck disable=SC2001
  keep_pipeline_images=$(echo "${raw_images}" | grep "$(echo "${keep_pipeline_tags}" | sed 's/.*/:&$/')")
  echo "Keeping latest pipeline images:"
  echo "${keep_pipeline_images}" | sed 's/^/  /' | sort
  raw_images=$(echo "${raw_images}" | grep -vF "${keep_pipeline_images}")
fi

# keep gitlab-runner-helper images
keep_gl_runner_images=$(echo "${raw_images}" | grep gitlab-runner-helper)
if (( "$(echo "${keep_gl_runner_images}" | wc -w)" > 0 )); then
  echo "Keeping gitlab-runner-helper images:"
  echo "${keep_gl_runner_images}" | sed 's/^/  /' | sort
  raw_images=$(echo "${raw_images}" | grep -vF "${keep_gl_runner_images}")
fi

echo "Images to remove:"
echo "${raw_images}" | sed 's/^/  /' | sort

if [[ ${IS_PRODUCTION:-} = [Tt]rue ]] || [[ ${CKI_DEPLOYMENT_ENVIRONMENT:-} = production ]]; then
    echo "${raw_images}" | xargs --no-run-if-empty docker image rm
else
    echo "Not removing images without CKI_DEPLOYMENT_ENVIRONMENT=production"
fi

echo "Done"
